﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Fish.Models;
using Fish.DAL;

namespace Fish.Controllers
{

    /** 
   * This class is responsible for creating, displaying, and editing templates.
   */
    [Authorize]
    public class TemplatesController : Controller
    {
        
        static String[] TagsGlobal;
        static String[] TagsDefaultGlobal;
        private FishContext db = new FishContext();

        // GET: /Templates/
        public ActionResult Index()
        {
            var templates = db.Templates.Include(t => t.User);
            int userIdint = int.Parse(Session["userID"].ToString());
            return View(templates.Where(t => (t.UsersID == null)
                || (t.UsersID == userIdint)).ToList());
        }

        // GET: /Templates/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Templates templates = db.Templates.Find(id);
            if (templates == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(templates);
        }

        // GET: /Templates/Create
        public ActionResult Create()
        {
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username");
            return View();
        }

        // POST: /Templates/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name,Image,Description,UsersID,Created,Modified")] Templates templates, HttpPostedFileBase uploadedImage)
        {
            if (ModelState.IsValid)
            {
                byte[] imageBytes = null;

                if (uploadedImage != null)
                {

                    int imageLength = uploadedImage.ContentLength;
                    imageBytes = new byte[imageLength];
                    uploadedImage.InputStream.Read(imageBytes, 0, imageLength);
                }
                templates.TemplateImage = imageBytes;
                if (TagsGlobal != null)
                {
                    templates.Customized = new List<Customizeds>();
                    for (int i = 0; i < TagsGlobal.Length;)
                    {
                        Customizeds cus = new Customizeds();
                        cus.fieldContent = new List<customizedString>();
                        cus.fieldTitle = new List<customizedString>();
                        cus.fieldType = new List<customizedString>();
                        cus.Name = TagsGlobal[i].Replace("*","");
                        System.Diagnostics.Debug.WriteLine("Name: " + TagsGlobal[i].Replace("*", ""));
                        i++;
                        while (i < TagsGlobal.Length && !TagsGlobal[i].Contains("*"))
                        {
                            System.Diagnostics.Debug.WriteLine("Title: " + TagsGlobal[i]);
                            customizedString c = new customizedString();
                            c.text = TagsGlobal[i];
                            cus.fieldTitle.Add(c);
                            i++;
                            System.Diagnostics.Debug.WriteLine("Type: " + TagsGlobal[i]);
                            customizedString c2 = new customizedString();
                            c2.text = TagsGlobal[i];
                            cus.fieldType.Add(c2);
                            i++;
                        }
                        db.Customizeds.Add(cus);
                        db.SaveChanges();
                        templates.Customized.Add(cus);
                    }
                }
                if (TagsDefaultGlobal != null && TagsDefaultGlobal.Length>0)
                {
                    templates.Tabs = new List<tabNumber>();
                    for(short i = 0;i<TagsDefaultGlobal.Length;i++){
                        if (int.Parse(TagsDefaultGlobal[i]) == 1) { 
                        templates.Tabs.Add(new tabNumber { number = i });
                        System.Diagnostics.Debug.WriteLine("Tabs: " + i);
                        }
                    }

                }
                db.Templates.Add(templates);
                db.SaveChanges();
                if (Session["eventName"] != null && Session["eventName"].ToString().Length != 0)
                {
                    Session["eventTemplate"] = templates.ID;
                    return RedirectToAction("Create", "Events");
                }
                return RedirectToAction("Index");
            }

            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username", templates.UsersID);
            return View(templates);
        }


   
    /** 
   * This method is responsible for viewing the template image uploaded by the user .
   */
        [HttpGet]
        public ActionResult ViewImage(int id)
        
        {
            if (id == 1)
            {
                System.Diagnostics.Debug.WriteLine("IN 1");
                return new FilePathResult("~/Repository/birthdays.jpg", "image/jpg");
            }

            if (id == 2)
            {
                return new FilePathResult("~/Repository/DishParty.jpg", "image/jpg");
            }
            if (id == 3)
            {
                return new FilePathResult("~/Repository/outing.jpg", "image/jpg");
            }
            Templates template = db.Templates.Find(id);
            byte[] buffer = template.TemplateImage;
            if (buffer != null)
                return File(buffer, "image/jpg", string.Format("{0}.jpg", id));
            else
                return File("~/Content/Images/no-image.gif", "image/jpg", string.Format("{0}.jpg", id));

           
        }
        // GET: /Templates/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Templates templates = db.Templates.Find(id);
            if (templates == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username", templates.UsersID);
            return View(templates);
        }

        // POST: /Templates/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name,Image,Description,UsersID,Created,Modified")] Templates templates)
        {
            if (ModelState.IsValid)
            {
                db.Entry(templates).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.UsersID = new SelectList(db.Users, "ID", "Username", templates.UsersID);
            return View(templates);
        }

        // GET: /Templates/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Templates templates = db.Templates.Find(id);
            if (templates == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(templates);
        }

        // POST: /Templates/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Templates templates = db.Templates.Find(id);
            db.Templates.Remove(templates);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public void SaveTabs(String[] hopa,String[] lala)
        {
            TagsGlobal = hopa;
            TagsDefaultGlobal = lala;

        }
    }
}
